#include <iostm8s103f3.h>
#include <intrinsics.h>

unsigned int TimerCnt = 0;
unsigned int TargetCnt1 = 2000;
unsigned int TargetCnt2 = 10000;

int main( void )
{
  // setup clock
  CLK_CKDIVR &= (unsigned char)(~0x18);  // 16MHz high speed internal clock
  
  //LED: B5
  PB_DDR |= 0x20;  // output
  PB_CR1 |= 0x20;  // push pull
  PB_CR2 |= 0x20;  // 10MHz output speed
  
  // setup timer 2; generate a 10KHz(100us) interrupt
  TIM2_PSCR = 0x04;   // prescaler = 16; 16MHz/(2^4)=1MHz
  TIM2_ARRH = 0;      // high byte of 99(100-1)
  TIM2_ARRL = 99;     // low byte of 99(100-1)
  TIM2_IER = 0x01;    // update interrupts enabled
  TIM2_CR1 = 0x01;    // enable the timer
  
  // enable interrupt
  __enable_interrupt();
  
  while (1) {
    
  }
}


//  Timer 2 Overflow handler.
#pragma vector = TIM2_OVR_UIF_vector
__interrupt void TIM2_OVR_UIF_IRQHandler(void)
{
  TimerCnt++;
  if (TimerCnt >= TargetCnt2)
    TimerCnt = 0;

  if (TimerCnt < TargetCnt1)
    PB_ODR &= 0xDF;  // LOW is ON
  else
    PB_ODR |= 0x20;  // HIGH if OFF
  TIM2_SR1 &= 0xFE;
}
